package model;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;

public class Cart {

    public static Hashtable<Integer, Integer> cart;

    public Cart() {
        cart = new Hashtable<Integer, Integer>();
    }

    public boolean find(int productId) {
        if (cart.containsKey(productId)) {
            return true;
        }
        return false;
    }

    public void purchase(int productId) {
        if (find(productId)) {
            int quantity = cart.get(productId);
            cart.remove(productId);
            cart.put(productId, quantity + 1);
        } else {
            cart.put(productId, 1);
        }
    }

    public void purchase(int productId, int quantity) {
        if (find(productId)) {
            cart.remove(productId);
        }
        if (!find(productId) && quantity > 0) {
            cart.put(productId, quantity);
        }
    }

    public static int getQuantity(Hashtable<Integer, Integer> ht) {
        int count = 0;
        if (ht == null) {
            return 0;
        } else {
            Enumeration e = ht.keys();
            while (e.hasMoreElements()) {
                int productId = (Integer) e.nextElement();
                count += ht.get(productId);
            }
            return count;
        }
    }

    public Hashtable<Integer, Integer> getCart() {
        return cart;
    }

    public void setCart(Hashtable<Integer, Integer> cart) {
        this.cart = cart;
    }

    public static double getTotal(Hashtable<Integer, Integer> ht) {
        DBFunction db = new DBFunction();
        double total = 0;
        if (ht == null) {
            return 0;
        } else {
            Enumeration e = ht.keys();
            while (e.hasMoreElements()) {
                int productId = (Integer) e.nextElement();
                try {
                    total = total + (ht.get(productId)) * (db.getProductPrice(productId));
                } catch (SQLException ex) {
                    ex.printStackTrace();
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                }
            }
            return total;
        }
    }
}
